package hamsterpolice.todo.data;

import android.util.Log;


public abstract class Model<T extends Model<T>> {
	
	private static final String TAG = "Model";
	private boolean isNew;
	private boolean dirty;
	private DataAdapter<T> dataAdapter;
	private long id;
	
	/**
	 * For use by Parcelable descendants
	 */
	protected Model() {}
	
	/**
	 * Constructor for creating a new object
	 * @param dataAdapter
	 */
	public Model(DataAdapter<T> dataAdapter){
		this.isNew = true;
		this.dirty = false;
		this.dataAdapter = dataAdapter;
	}
	
	public long getID(){
		return id;
	}
	
	protected void setID(long id){
		this.id = id;
	}
	
	public boolean isNew(){
		return isNew;
	}
	
	protected void setNew(boolean isNew){
		this.isNew = isNew;
	}
	
	public boolean isDirty(){
		return dirty;
	}
	
	protected void setDirty(boolean dirty){
		this.dirty = dirty;
	}
	
	public void delete(){
		if(!isNew()){
			dataAdapter.delete(getID());
		}
	}
	
	@SuppressWarnings("unchecked")
	public void save() throws DatabaseConstraintException{
		if(isNew()){
			this.setID(dataAdapter.insert((T) this));
		}
		else if(isDirty()){
			dataAdapter.update((T) this);
		}
		else{
			Log.i(TAG, "Save was called, but is a no-op because the model is not new or dirty.");
		}
		
		setNew(false);
		setDirty(false);
	}
}
